import L from 'leaflet'
import type { PointData, MergedPoint, TimeRange } from '../types'

// 计算两点间的地理距离（Haversine公式）
export const calculateDistance = (lat1: number, lon1: number, lat2: number, lon2: number): number => {
  const R = 6371 // 地球半径，单位：千米
  const dLat = (lat2 - lat1) * Math.PI / 180
  const dLon = (lon2 - lon1) * Math.PI / 180
  const a = 
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
    Math.sin(dLon/2) * Math.sin(dLon/2)
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
  return R * c
}

// 计算时间跨度
export const calculateTimeSpan = (time1: string, time2: string): string => {
  const date1 = new Date(time1)
  const date2 = new Date(time2)
  const diffMs = Math.abs(date2.getTime() - date1.getTime())
  
  const days = Math.floor(diffMs / (1000 * 60 * 60 * 24))
  const hours = Math.floor((diffMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
  const minutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60))
  
  if (days > 0) {
    return `${days}天 ${hours}小时 ${minutes}分钟`
  } else if (hours > 0) {
    return `${hours}小时 ${minutes}分钟`
  } else {
    return `${minutes}分钟`
  }
}

// 合并重合点的函数
export const mergeOverlappingPoints = (points: PointData[], threshold: number = 0.001): MergedPoint[] => {
  const merged: MergedPoint[] = []
  
  points.forEach(point => {
    // 查找是否有重合的点
    const existingPoint = merged.find(mp => 
      Math.abs(mp.longitude - point.longitude) < threshold && 
      Math.abs(mp.latitude - point.latitude) < threshold
    )
    
    if (existingPoint) {
      // 如果找到重合点，添加到现有点的内容中
      existingPoint.contents.push({
        time: point.time,
        hoverContent: point.hoverContent,
        location: point.location
      })
      existingPoint.count++
    } else {
      // 如果没有重合点，创建新的合并点
      merged.push({
        longitude: point.longitude,
        latitude: point.latitude,
        contents: [{
          time: point.time,
          hoverContent: point.hoverContent,
          location: point.location
        }],
        count: 1
      })
    }
  })
  
  return merged
}

// 检查点是否在选中的时间范围内
export const isPointInTimeRange = (pointTime: string, timeRange: TimeRange | null): boolean => {
  if (!timeRange) return true
  const time = new Date(pointTime)
  return time >= timeRange.start && time <= timeRange.end
}

// 创建自定义图标 - 支持时间范围颜色
export const createCustomIcon = (count: number, isSelected: boolean = false, mergedPoint?: MergedPoint, selectedTimeRange?: TimeRange | null) => {
  const size = count > 1 ? 30 : 20
  
  // 检查所有时间点是否都在选中范围内
  let color = '#ff0000' // 默认红色
  if (mergedPoint && selectedTimeRange) {
    const allInRange = mergedPoint.contents.every(content => 
      isPointInTimeRange(content.time, selectedTimeRange)
    )
    const someInRange = mergedPoint.contents.some(content => 
      isPointInTimeRange(content.time, selectedTimeRange)
    )
    
    if (allInRange) {
      color = '#ff0000' // 红色：完全在范围内
    } else if (someInRange) {
      color = '#ff6666' // 浅红色：部分在范围内
    } else {
      color = '#ffaaaa' // 很浅的红色：完全不在范围内
    }
  }
  
  if (isSelected) {
    color = '#00ff00' // 选中时为绿色
  }
  
  const borderColor = isSelected ? '#00cc00' : '#ffffff'
  
  return L.divIcon({
    className: 'custom-marker',
    html: `
      <div style="
        background-color: ${color}; 
        width: ${size}px; 
        height: ${size}px; 
        border-radius: 50%; 
        border: 3px solid ${borderColor}; 
        box-shadow: 0 0 10px rgba(0,0,0,0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: bold;
        color: white;
        font-size: ${count > 1 ? '12px' : '10px'};
        ${isSelected ? 'animation: pulse 1s infinite;' : ''}
      ">
        ${count > 1 ? count : ''}
      </div>
    `,
    iconSize: [size, size],
    iconAnchor: [size/2, size/2]
  })
}

// 创建弹窗内容
export const createPopupContent = (mergedPoint: MergedPoint, selectedTimeRange?: TimeRange | null) => {
  if (mergedPoint.count === 1) {
    const isInRange = isPointInTimeRange(mergedPoint.contents[0].time, selectedTimeRange || null)
    return `
      <div style="min-width: 200px;">
        <div style="
          background: rgba(255, 102, 0, 0.1); 
          padding: '8px'; 
          borderRadius: '6px';
          marginBottom: '8px';
          border: '1px solid rgba(255, 102, 0, 0.2)';
        ">
          <div style="font-weight: bold; color: #ff6600; fontSize: '12px';">📍 地点</div>
          <div style="fontSize: '13px'; color: '#333';">${mergedPoint.contents[0].location}</div>
        </div>
        <strong>${mergedPoint.contents[0].hoverContent}</strong><br/>
        <small>坐标: ${mergedPoint.latitude.toFixed(4)}, ${mergedPoint.longitude.toFixed(4)}</small><br/>
        <small>时间: ${mergedPoint.contents[0].time}</small><br/>
        <small style="color: ${isInRange ? '#ff0000' : '#aaa'}">
          ${isInRange ? '✓ 在时间范围内' : '✗ 不在时间范围内'}
        </small>
      </div>
    `
  } else {
    const contentList = mergedPoint.contents
      .map((content, index) => {
        const isInRange = isPointInTimeRange(content.time, selectedTimeRange || null)
        return `
          <div style="
            padding: 8px 0; 
            border-bottom: ${index < mergedPoint.contents.length - 1 ? '1px solid #eee' : 'none'};
          ">
            <div style="
              background: rgba(255, 102, 0, 0.1); 
              padding: 4px 6px; 
              borderRadius: 4px;
              marginBottom: 4px;
              fontSize: 11px;
              color: #ff6600;
              fontWeight: bold;
            ">
              📍 ${content.location}
            </div>
            <strong>${content.hoverContent}</strong><br/>
            <small>时间: ${content.time}</small><br/>
            <small style="color: ${isInRange ? '#ff0000' : '#aaa'}">
              ${isInRange ? '✓ 在时间范围内' : '✗ 不在时间范围内'}
            </small>
          </div>
        `
      }).join('')
    
    return `
      <div style="min-width: 250px; max-height: 300px; overflow-y: auto;">
        <div style="
          background: #f0f0f0; 
          padding: 5px 10px; 
          margin: -10px -10px 10px -10px; 
          font-weight: bold;
          color: #333;
        ">
          重合点位 (${mergedPoint.count}个)
        </div>
        <div style="font-size: 12px; color: #666; margin-bottom: 10px;">
          坐标: ${mergedPoint.latitude.toFixed(4)}, ${mergedPoint.longitude.toFixed(4)}
        </div>
        ${contentList}
      </div>
    `
  }
} 